""" article仓储操作 """
import time
from sqlalchemy.orm import Session, joinedload
from model.article import Article
from schema.article import ArticleUpdate, ArticleCreate


def get_articles(db: Session, page: int, perPage: int):
    """ 分页获取文章列表 """
    arts = db.query(Article).order_by(Article.updated_at).offset(
        (page - 1) * perPage).limit(perPage).options(joinedload(Article.category)).all()
    arts.reverse()
    return arts


def get_count(db: Session):
    """ 获取全部文章数量 """
    return db.query(Article).count()


def get_by_id(db: Session, article_id: int):
    """ 通过id获取文章 """
    return db.query(Article).filter(Article.id == article_id).options(joinedload(Article.category)).first()


def get_by_title(db: Session, article_title: str):
    """ 通过文章标题搜索文章 """
    return db.query(Article).filter(Article.title.contains(article_title)).options(joinedload(Article.category)).all()


def create_article(db: Session, art: ArticleCreate):
    """ 新增文章 """
    article = Article(title=art.title,
                      description=art.description,
                      cate_id=art.cate_id,
                      content=art.content,
                      created_at=int(time.time()),
                      updated_at=int(time.time()))
    db.add(article)
    db.commit()
    db.refresh(article)
    return article


def update_article(db: Session, article_id: int, update_article: ArticleUpdate):
    """ 更新文章信息 """
    article = db.query(Article).filter(
        Article.id == article_id).first()

    if article:
        update_dict = update_article.dict(exclude_unset=True)
        for k, v in update_dict.items():
            setattr(article, k, v)
        setattr(article, "updated_at", int(time.time()))
        db.commit()
        db.flush()
        db.refresh(article)
        return article


def delete_article(db: Session, article_id: int):
    """ 删除文章 """
    article = db.query(Article).filter(
        Article.id == article_id).first()
    if article:
        db.delete(article)
        db.commit()
        db.flush()
        return article
